package com.example.securityconfiggen.service;

import com.dragonpass.global.common.lite.security.util.SecurityUtil;
import org.springframework.stereotype.Service;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import static com.dragonpass.global.common.lite.security.constants.SecurityConstants.ENCRYPT_KEY;
import static com.dragonpass.global.common.lite.security.constants.SecurityConstants.SECRET_KEY;

@Service
public class PropertiesService {

    /**
     * 处理properties内容，同时返回MD5和Base64两种加密结果
     * 
     * @param projectName 项目名称
     * @param propertiesContent properties格式的内容
     * @return 包含两种加密结果的Map
     */
    public Map<String, String> processProperties(String projectName, String propertiesContent) throws InvalidAlgorithmParameterException, NoSuchPaddingException, IllegalBlockSizeException, NoSuchAlgorithmException, BadPaddingException, InvalidKeySpecException, InvalidKeyException {
        try {
            // 加载properties内容
            Properties props = new Properties();
            props.load(new ByteArrayInputStream(propertiesContent.getBytes()));

            // 创建敏感配置的properties对象
            Properties securityProps = new Properties();
            // 创建keyvault配置的properties对象
            Properties keyVaultProps = new Properties();
            
            // 遍历properties，对value进行加密
            for (String key : props.stringPropertyNames()) {
                String value = props.getProperty(key);
                
//                dragonpass.security.keyvault.${biz-key}.secret-key=${serviceName}-${biz-key}-secret-key
//                dragonpass.security.keyvault.${biz-key}.encrypt-key=${serviceName}-${biz-key}-encrypt-key
                String concatStr = key.replaceAll("\\.", "-").replaceAll("_", "-");
                String key1 = projectName.concat("-").concat(concatStr).concat("-").concat(SECRET_KEY);
                String key2 = projectName.concat("-").concat(concatStr).concat("-").concat(ENCRYPT_KEY);
                securityProps.setProperty("dragonpass.security.keyvault.".concat(key).concat(".").concat(SECRET_KEY), key1);
                securityProps.setProperty("dragonpass.security.keyvault.".concat(key).concat(".").concat(ENCRYPT_KEY), key2);

                String k = SecurityUtil.generateSecret();
                keyVaultProps.setProperty(key1, k);
                keyVaultProps.setProperty(key2, SecurityUtil.encrypt(value, k));
            }

            // 使用StringBuilder直接构建结果字符串，避免特殊字符被转义
            StringBuilder md5Result = new StringBuilder();
            md5Result.append("# ").append(projectName).append(" - 项目本地配置结果\n");
            for (String key : securityProps.stringPropertyNames()) {
                md5Result.append(key).append("=").append(securityProps.getProperty(key)).append("\n");
            }

            StringBuilder base64Result = new StringBuilder();
            base64Result.append("# ").append(projectName).append(" - Keyvault配置结果\n");
            for (String key : keyVaultProps.stringPropertyNames()) {
                base64Result.append(key).append("=").append(keyVaultProps.getProperty(key)).append("\n");
            }
            
            // 生成KeyVault执行命令
            StringBuilder keyvaultCommands = new StringBuilder();
            keyvaultCommands.append("# ").append(projectName).append(" - KeyVault执行命令\n");
            for (String key : keyVaultProps.stringPropertyNames()) {
                String value = keyVaultProps.getProperty(key);
                keyvaultCommands.append("az keyvault secret set --vault-name YOUR-VAULT-NAME --name ").append(key).append(" --value \"").append(value).append("\"\n");
            }

            // 返回包含两种加密结果的Map
            Map<String, String> results = new HashMap<>();
            results.put("md5", md5Result.toString());
            results.put("base64", base64Result.toString());
            results.put("keyvaultCommands", keyvaultCommands.toString());
            return results;
            
        } catch (IOException e) {
            throw new RuntimeException("处理Properties内容时出错", e);
        }
    }
    
    /**
     * 对字符串进行MD5加密
     * 
     * @param input 输入字符串
     * @return MD5加密后的字符串
     */
    private String md5Encrypt(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            BigInteger no = new BigInteger(1, messageDigest);
            
            // 将BigInteger转换为16进制字符串
            String hashtext = no.toString(16);
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("MD5加密失败", e);
        }
    }
    
    /**
     * 对字符串进行Base64加密
     * 
     * @param input 输入字符串
     * @return Base64加密后的字符串
     */
    private String base64Encrypt(String input) {
        return Base64.getEncoder().encodeToString(input.getBytes());
    }
} 